package com.xyy.controller;

import com.xyy.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 图片访问控制器
 */
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageController {

    @Autowired
    private FileService fileService;

    /**
     * 获取图片文件
     * @param filePath 文件路径（相对于picture目录）
     * @return 图片文件
     */
    @GetMapping("/{filePath:.*}")
    public ResponseEntity<Resource> getImage(@PathVariable String filePath) {
        try {
            // 获取文件的完整路径
            String fullPath = fileService.getFullPath(filePath);
            if (fullPath == null) {
                return ResponseEntity.notFound().build();
            }

            Path path = Paths.get(fullPath);
            Resource resource = new UrlResource(path.toUri());

            if (resource.exists() && resource.isReadable()) {
                // 根据文件扩展名设置Content-Type
                String contentType = getContentType(filePath);
                
                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                log.warn("图片文件不存在或无法读取: {}", filePath);
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            log.error("图片文件路径错误: {}", filePath, e);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("获取图片文件失败: {}", filePath, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据文件扩展名获取Content-Type
     */
    private String getContentType(String filePath) {
        if (filePath == null) {
            return "image/jpeg";
        }
        
        String lowerPath = filePath.toLowerCase();
        if (lowerPath.endsWith(".jpg") || lowerPath.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (lowerPath.endsWith(".png")) {
            return "image/png";
        } else if (lowerPath.endsWith(".gif")) {
            return "image/gif";
        } else if (lowerPath.endsWith(".bmp")) {
            return "image/bmp";
        } else if (lowerPath.endsWith(".webp")) {
            return "image/webp";
        } else {
            return "image/jpeg"; // 默认
        }
    }
}
